package com.danceforyou.payment.controller;

import com.danceforyou.common.model.view.BizData4Page;
import com.danceforyou.common.restful.exception.BizExceptionEnum;
import com.danceforyou.common.util.AssertUtil;
import com.danceforyou.common.util.Constants;
import com.danceforyou.common.util.ExcelExportUtil;
import com.danceforyou.common.util.StringUtil;
import com.danceforyou.common.vo.SqlOrderEnum;
import com.danceforyou.payment.model.PaymentDO;
import com.danceforyou.payment.model.PaymentVoucherDO;
import com.danceforyou.payment.service.PaymentService;
import com.danceforyou.payment.service.PaymentVoucherService;
import com.danceforyou.payment.vo.PaymentExcelVO;
import com.danceforyou.payment.vo.PaymentVO;
import com.danceforyou.user.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;
    @Autowired
    private PaymentVoucherService paymentVoucherService;
    @Autowired(required = false)
    private HttpSession session;

    private void dealPaymentContidion(Map<String, Object> condition) {
        for (Map.Entry<String, Object> entry : condition.entrySet()) {
            if (StringUtil.isBlank(entry.getValue().toString())) {
                condition.put(entry.getKey(), null);
            }
        }
        if (condition.get("numberType") != null) {
            switch (condition.get("numberType").toString()) {
                case "1":
                    //付款金额
                    if (condition.get("numberStart") != null) {
                        condition.put("payMoneyStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("payMoneyEnd", condition.get("numberEnd"));
                    }
                    break;
                case "2":
                    //执行价
                    if (condition.get("numberStart") != null) {
                        condition.put("quotedPriceStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("quotedPriceEnd", condition.get("numberEnd"));
                    }
                    break;
                case "3":
                    //成本价
                    if (condition.get("numberStart") != null) {
                        condition.put("costPriceStart", condition.get("numberStart"));
                    }
                    if (condition.get("numberEnd") != null) {
                        condition.put("costPriceEnd", condition.get("numberEnd"));
                    }
                    break;
                default: break;
            }
        }
        if (condition.get("dateType") != null) {
            switch (condition.get("dateType").toString()) {
                case "1":
                    //创建日期
                    if (condition.get("dateStart") != null) {
                        condition.put("createDateStart", condition.get("dateStart"));
                    }
                    if (condition.get("dateEnd") != null) {
                        condition.put("createDateEnd", condition.get("dateEnd"));
                    }
                    break;
                case "2":
                    //审核日期
                    if (condition.get("dateStart") != null) {
                        condition.put("auditDateStart", condition.get("dateStart"));
                    }
                    if (condition.get("dateEnd") != null) {
                        condition.put("auditDateEnd", condition.get("dateEnd"));
                    }
                    break;
                case "3":
                    //支付日期
                    if (condition.get("dateStart") != null) {
                        condition.put("payDateStart", condition.get("dateStart"));
                    }
                    if (condition.get("dateEnd") != null) {
                        condition.put("payDateEnd", condition.get("dateEnd"));
                    }
                    break;
                case "4":
                    //投放日期
                    if (condition.get("dateStart") != null) {
                        condition.put("putDateStart", condition.get("dateStart"));
                    }
                    if (condition.get("dateEnd") != null) {
                        condition.put("putDateEnd", condition.get("dateEnd"));
                    }
                    break;
                default: break;
            }
        }
        if (condition.get("putAddress") != null && condition.get("putAddress").toString().equals("全部")) {
            condition.remove("putAddress");
        }
        if (condition.get("payAccount") != null && condition.get("payAccount").toString().equals("全部")) {
            condition.remove("payAccount");
        }
        if (condition.get("status") != null && condition.get("status").toString().equals("ALL")) {
            condition.remove("status");
        }
    }

    /**
     * 根据排期ID获取付款记录
     * @param orderId 排期ID
     * @return List<PaymentVO>
     */
    @RequestMapping(value = "/listPaymentByOrderId", method = RequestMethod.GET)
    public List<PaymentVO> listPaymentByOrderId(Long orderId) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        return paymentService.queryList(new HashMap<String, Object>(){{
            put("orderId", orderId);
            put("isDelete", false);
        }});
    }

    /**
     * 分页查询我的付款记录
     * @param bizData4Page BizData4Page
     * @return BizData4Page
     */
    @RequestMapping(value = "/querySelfPaymentPage", method = RequestMethod.GET)
    public BizData4Page<PaymentVO> querySelfPaymentPage(BizData4Page<PaymentVO> bizData4Page) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        Map<String, Object> condition = bizData4Page.getCondition();
        dealPaymentContidion(condition);
        condition.put("createUserId", loginUser.getId());
        condition.put("isDelete", false);
        bizData4Page.setStat(true);
        paymentService.queryPageByDataPerm(bizData4Page);
        return bizData4Page;
    }

    /**
     * 分页查询待审核付款记录
     * @param bizData4Page BizData4Page
     * @return BizData4Page
     */
    @RequestMapping(value = "/queryAuditPaymentPage", method = RequestMethod.GET)
    public BizData4Page<PaymentVO> queryAuditPaymentPage(BizData4Page<PaymentVO> bizData4Page) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        Map<String, Object> condition = bizData4Page.getCondition();
        dealPaymentContidion(condition);
        condition.putIfAbsent("status", Constants.PAYMENT_STATUS_FILLIN);
        condition.put("isDelete", false);
        bizData4Page.setStat(true);
        paymentService.queryPageByDataPerm(bizData4Page);
        return bizData4Page;
    }

    /**
     * 分页查询待支付付款记录
     * @param bizData4Page BizData4Page
     * @return BizData4Page
     */
    @RequestMapping(value = "/queryPayPaymentPage", method = RequestMethod.GET)
    public BizData4Page<PaymentVO> queryPayPaymentPage(BizData4Page<PaymentVO> bizData4Page) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        Map<String, Object> condition = bizData4Page.getCondition();
        dealPaymentContidion(condition);
        condition.putIfAbsent("statusList", new int[]{Constants.PAYMENT_STATUS_PASSED, Constants.PAYMENT_STATUS_FINISH});
        condition.put("isDelete", false);
        bizData4Page.setStat(true);
        paymentService.queryPageByDataPerm(bizData4Page);
        return bizData4Page;
    }

    /**
     * 分页查询统计付款记录
     * @param bizData4Page BizData4Page
     * @return BizData4Page
     */
    @RequestMapping(value = "/queryStatPaymentPage", method = RequestMethod.GET)
    public BizData4Page<PaymentVO> queryStatPaymentPage(BizData4Page<PaymentVO> bizData4Page) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        Map<String, Object> condition = bizData4Page.getCondition();
        dealPaymentContidion(condition);
        condition.put("isDelete", false);
        if (loginUser.getRole().getRoleType().equals(Constants.ROLE_MJB_CODE)) {
            condition.putIfAbsent("mediumUserId", loginUser.getId());
        }
        if (loginUser.getRole().getRoleType().equals(Constants.ROLE_XSB_CODE)) {
            condition.putIfAbsent("orderUserId", loginUser.getId());
        }
        bizData4Page.setStat(true);
        paymentService.queryPageByDataPerm(bizData4Page);
        return bizData4Page;
    }

    /**
     * 新建付款
     * @param payment 付款信息
     * @return boolean
     */
    @RequestMapping(value = "/savePaymentInfo", method = RequestMethod.POST)
    public boolean savePaymentInfo(PaymentDO payment) {
        paymentService.saveInfo(payment);
        return true;
    }

    /**
     * 修改付款
     * @param payment 付款信息
     * @return boolean
     */
    @RequestMapping(value = "/updatePaymentInfo", method = RequestMethod.POST)
    public boolean updatePaymentInfo(PaymentDO payment) {
        paymentService.updateInfo(payment);
        return true;
    }

    /**
     * 删除付款
     * @param ids 付款IDS
     * @return int
     */
    @RequestMapping(value = "/deletePaymentInfoByIds", method = RequestMethod.POST)
    public int deleteInfoByIds(String ids) {
        return paymentService.deleteInfoByIds(ids);
    }

    /**
     * 审核通过付款申请
     * @param ids 付款IDS
     * @return int
     */
    @RequestMapping(value = "/setPaymentAuditPass", method = RequestMethod.POST)
    public int setPaymentAuditPass(String ids) {
        return paymentService.setPaymentAuditPass(ids);
    }

    /**
     * 审核不通过付款申请
     * @param ids 付款IDS
     * @param auditDesc 审核意见
     * @return int
     */
    @RequestMapping(value = "/setPaymentAuditNoPass", method = RequestMethod.POST)
    public int setPaymentAuditNoPass(String ids, String auditDesc) {
        return paymentService.setPaymentAuditNoPass(ids, auditDesc);
    }

    /**
     * 支付付款申请
     * @param fileList 付款凭证
     * @param ids 付款IDS
     * @return int
     */
    @RequestMapping(value = "/setPaymentPayed", method = RequestMethod.POST)
    public int setPaymentPayed(@RequestParam MultipartFile[] fileList, String ids) {
        return paymentService.setPaymentPayed(fileList, ids);
    }

    /**
     * 获取付款记录凭证列表
     * @param paymentId 付款ID
     * @return List<PaymentVoucherDO>
     */
    @RequestMapping(value = "/listPaymentVoucherByPaymentId", method = RequestMethod.GET)
    public List<PaymentVoucherDO> listPaymentVoucherByPaymentId(Long paymentId) {
        return paymentVoucherService.listByProperty("paymentId", paymentId);
    }

    /**
     * 分页查询统计付款记录
     * @param condition 查询条件
     */
    @RequestMapping(value = "/exportStatPayment", method = RequestMethod.GET)
    public void exportStatPayment(@RequestParam Map<String, Object> condition, HttpServletResponse response) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        dealPaymentContidion(condition);
        condition.put("isDelete", false);
        if (loginUser.getRole().getRoleType().equals(Constants.ROLE_MJB_CODE)) {
            condition.putIfAbsent("mediumUserId", loginUser.getId());
        }
        if (loginUser.getRole().getRoleType().equals(Constants.ROLE_XSB_CODE)) {
            condition.putIfAbsent("orderUserId", loginUser.getId());
        }
        List<PaymentVO> paymentList = paymentService.queryList(condition, condition.get("orderBy").toString(), condition.get("sortBy").toString().equals("ASC") ? SqlOrderEnum.ASC : SqlOrderEnum.DESC);
        List<Object> excelVOList = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (PaymentVO payment : paymentList) {
            PaymentExcelVO excelVO = new PaymentExcelVO();
            excelVO.setId(payment.getId());
            excelVO.setOrderId(payment.getOrderId());
            excelVO.setCustomerBrand(payment.getCustomerBrand());
            excelVO.setMediumName(payment.getMediumName());
            excelVO.setMediumType(payment.getMediumType() == 1 ? "公众号" : "视频号");
            excelVO.setPutDate(dateFormat.format(payment.getPutDate()));
            excelVO.setPutAddress(payment.getPutAddress());
            excelVO.setQuotedPrice(payment.getQuotedPrice());
            excelVO.setCostPrice(payment.getCostPrice());
            excelVO.setPayAccount(payment.getPayAccount());
            excelVO.setPayMoney(payment.getPayMoney());
            excelVO.setRecName(payment.getRecName());
            excelVO.setRecAccount(payment.getRecAccount());
            excelVO.setRecBank(payment.getRecBank());
            excelVO.setCreateUserName(payment.getCreateUserName());
            excelVO.setCreateDate(dateTimeFormat.format(payment.getCreateDate()));
            excelVO.setCreateDesc(payment.getCreateDesc());
            excelVO.setAuditUserName(payment.getAuditUserName());
            excelVO.setAuditDate(dateTimeFormat.format(payment.getAuditDate()));
            excelVO.setAuditDesc(payment.getAuditDesc());
            excelVO.setPayUserName(payment.getPayUserName());
            excelVO.setPayDate(dateTimeFormat.format(payment.getPayDate()));
            excelVO.setMediumUserName(payment.getMediumUserName());
            excelVO.setOrderUserName(payment.getOrderUserName());
            switch (payment.getStatus()) {
                case Constants.PAYMENT_STATUS_FILLIN: excelVO.setStatus("待审核"); break;
                case Constants.PAYMENT_STATUS_NOPASS: excelVO.setStatus("审核不通过"); break;
                case Constants.PAYMENT_STATUS_PASSED: excelVO.setStatus("待支付"); break;
                case Constants.PAYMENT_STATUS_FINISH: excelVO.setStatus("支付完成"); break;
            }
            excelVOList.add(excelVO);
        }
        String[] fieldTitle = {"付款编号", "排期编号", "客户品牌", "媒体名称", "媒体类型", "投放日期", "投放位置", "执行价", "成本价", "付款账户",
                "付款金额", "收方名称", "收方账号", "收方开户行", "申请人", "申请时间", "申请事由", "审核人", "审核时间", "审核意见",
                "支付人", "支付时间", "对接媒介", "对接销售", "状态"};
        int[] fieldWidth = {10, 10, 20, 20, 10, 10, 10, 10, 10, 15,
                10, 10, 20, 20, 10, 20, 40, 10, 20, 40,
                10, 20, 10, 10, 10};
        ExcelExportUtil.export("付款记录列表", fieldTitle, fieldWidth, excelVOList, response);
    }
}
